#!/usr/bin/env python

import json, os

import mantux_data.commands
import mantux_data.templates

FOLDER = ".mantux"

class Mantux ( object ):
	def __init__ ( self ):
		dirname, filename = os.path.split ( os.path.abspath ( __file__ ) )

		self.basedir = dirname
		self.repos = {}
		self.deps  = {}
		self._exclude_dirs = {}

		self.cfg = { "repos" : [] }

		self._load_cfg ()

		self.commands = {}

		self.init ( [ os.path.join ( dirname, "repos" ) ] + list ( self.cfg [ 'repos' ] ) )

		self._set_commands ()

	def init ( self, paths = None ):
		if paths:
			self._scan_repos ( paths )

	def call ( self, command, args = None ):
		cmd = self.commands [ command ]

		cmd [ 'func' ] ( self, args )

	def exclude ( self, name = "---", dirname = "---" ):
		if not self._exclude_dirs:
			self._deps_load ()

		res = False

		if name in self.deps: res = True
		if dirname in self._exclude_dirs and os.path.exists ( dirname ): res = True

		#print "EXCLUDE: %s - %s - %d" % ( name, dirname, res )

		return res

	def _set_commands ( self ):
		mantux_data.commands.install_commands ( self )
		mantux_data.templates.install_commands ( self )


	def _write_if_missing ( self, fname, txt ):
		if os.path.exists ( fname ): return
	
		open ( fname, "w" ).write ( txt )
		
	def _scan_repos ( self, paths ):
		import glob

		for path in paths:
			for f in glob.glob ( os.path.join ( path, "*.json" ) ):
				a = self._json_load ( f )
				for x in a:
					self.repos [ x [ 'name' ] ] = x

	def _load_cfg ( self ):
		"""	
		Reads configuration from the following sources:

			- /etc/mantux/config
			- ~/.mantux/config
			- (project dir)/.mantux/config
		"""
		self._load_config ( "/etc/mantux/config" )
		self._load_config ( os.path.join ( os.path.expanduser ( "~" ), FOLDER, "config" ) )

		cwd = self._find_project_root ()
		if cwd: self._load_config ( os.path.join ( cwd, FOLDER, "config" ) )

		self.cfg [ 'repos' ] = set ( self.cfg [ 'repos' ] )
		
		

	def _load_config ( self, fname ):
		if not os.path.exists ( fname ): return False

		repos = self.cfg.get ( 'repos', [] )

		data = self._json_load ( fname ) 
		self.cfg.update ( data )

		self.cfg [ 'repos' ] = repos + self.cfg.get ( "repos", [] )

		return True

	def _find_project_root ( self ):
		cwd = os.getcwd ()
		while len ( cwd ) > 1:
			if os.path.exists ( os.path.join ( cwd, FOLDER ) ): return cwd
			cwd = os.path.dirname ( cwd )

		return False


	def _json_load ( self, fname ):
		try:
			return json.loads ( open ( fname ).read () )
		except:
			print "ERROR: cannot parse / load file : %s" % fname
		return ""

	def _deps_add ( self, data, version, install_dir, dirname ):
		data [ 'version' ] = version
		data [ 'install_dir' ] = install_dir
		data [ 'dirname' ] = dirname

		self.deps [ data [ 'name' ] ] = data
		self._deps_save ()

	def _deps_save ( self ):
		cwd = self._find_project_root ()
		
		open ( os.path.join ( cwd, FOLDER, "deps" ), "w" ).write ( json.dumps ( self.deps, indent = 4 ) )

	def _deps_load ( self ):
		cwd = self._find_project_root ()

		if not cwd:
			print "ERROR: current project not inited. Use 'init'"
			return

		self.deps = self._json_load ( os.path.join ( cwd, FOLDER, "deps" ) )

		self._exclude_dirs = {}

		for k, v in self.deps.iteritems ():
			name = os.path.join ( v.get ( "install_dir", "" ), v [ 'dirname' ] )
			self._exclude_dirs [ name ] = v

		

	def _go_to_install_dir ( self, data ):
		cwd = self._find_project_root ()

		if data.get ( "install_dir" ):
			install_dir = data [ 'install_dir' ]
		else:
			install_dir = self.cfg.get ( "install_dir" )

		os.chdir ( cwd )

		if not install_dir: install_dir = "."

		if not os.path.exists ( install_dir ):
			os.makedirs ( install_dir )

		os.chdir ( install_dir )

		return self._get_cwd ()

	def _get_cwd ( self ):
		cwd = self._find_project_root ()
		real_cwd = os.getcwd ()

		res = real_cwd.replace ( cwd, "" ) [ 1 : ]

		return res

		
		
				
if __name__ == '__main__':
	from mantux_data.cmd import MantuxCmd

	cmd = MantuxCmd ( Mantux () )
	cmd.go ()
